package Filter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jdk.nashorn.internal.runtime.regexp.joni.Regex;

@WebFilter("/LoginFIlter")
public class LoginFIlter implements Filter {
	private String Loginpath;
	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		String path=request.getRequestURI();
		
        if(path.contains("Resources")){
            chain.doFilter(req, resp);
            return;
        }
       	if (request.getServletPath().equals(Loginpath)||request.getServletPath().equals("/Login")||path.contains("/Login")) {
            chain.doFilter(request,response);
            return;
        }
	        
		if(session.getAttribute("username")==null||session.getAttribute("username").equals("")){
			resp.getWriter().println("<script type='text/javascript'>  alert('请先登录！'); </script>");
			response.sendRedirect("Login?method=logined");
			return;
			}
		chain.doFilter(request,response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		if(Loginpath==null)
			Loginpath = fConfig.getInitParameter("LoginPage");
	}

}
